/**
 * 封装AJAX请求工具
 * 支持GET/POST方法，可自定义请求头
 */

class Request {
  constructor(baseURL = 'www.baidu.com', timeout = 10000) {
    this.baseURL = baseURL
    this.timeout = timeout
    this.headers = {
      'Content-Type': 'application/json'
    }
  }

  /**
   * 设置请求头
   * @param {Object} headers - 请求头对象
   */
  setHeaders(headers) {
    this.headers = {
      ...this.headers,
      ...headers
    }
    return this
  }

  /**
   * GET请求
   * @param {string} url - 请求地址
   * @param {Object} params - 请求参数
   * @returns {Promise} 
   */
  get(url, params = {}) {
    return this._request('GET', url, params)
  }

  /**
   * POST请求
   * @param {string} url - 请求地址
   * @param {Object} data - 请求数据
   * @returns {Promise}
   */
  post(url, data = {}) {
    return this._request('POST', url, data)
  }

  /**
   * 发送请求
   * @private
   * @param {string} method - 请求方法
   * @param {string} url - 请求地址
   * @param {Object} data - 请求数据
   * @returns {Promise}
   */
  _request(method, url, data) {
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest()
      const requestUrl = this.baseURL + url

      // 处理GET请求参数
      if (method === 'GET' && Object.keys(data).length > 0) {
        const queryString = Object.entries(data)
          .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
          .join('&')
        url += `?${queryString}`
      }

      xhr.open(method, requestUrl, true)
      xhr.timeout = this.timeout

      // 设置请求头
      Object.entries(this.headers).forEach(([key, value]) => {
        xhr.setRequestHeader(key, value)
      })

      xhr.onload = () => {
        if (xhr.status >= 200 && xhr.status < 300) {
          try {
            const response = JSON.parse(xhr.responseText)
            resolve(response)
          } catch (e) {
            resolve(xhr.responseText)
          }
        } else {
          reject(new Error(`Request failed with status ${xhr.status}`))
        }
      }

      xhr.onerror = () => reject(new Error('Network error'))
      xhr.ontimeout = () => reject(new Error('Request timeout'))

      if (method === 'POST') {
        xhr.send(JSON.stringify(data))
      } else {
        xhr.send()
      }
    })
  }
}

// 创建默认实例
const request = new Request()

export default request